<template>
  <div class="addressList">
    <van-nav-bar
  title="收货地址"
  :right-text="myshow?'管理':'完成'"
  left-arrow
  @click-left="$router.go(-1)"
  @click-right="listshow"
/>
<van-address-list
  v-model="chosenAddressId"
  :list="list"
  :add-button-text="myshow ?'新增地址':'删除地址'"
  default-tag-text="默认"
  @add="onAdd"
  @edit="onEdit"
  @click-item="onitem"
/>
  </div>
</template>

<script>
import { getAddressList } from '@/api/pay'

export default {
  name: 'addressList',
  data () {
    return {
      myshow: true,
      chosenAddressId: '',
      // 地址列表数据
      list: [
        // {
        //   id: '1',
        //   name: '张三',
        //   tel: '13000000000',
        //   address: '浙江省杭州市西湖区文三路 138 号东方通信大厦 7 楼 501 室',
        //   isDefault: true
        // },
        // {
        //   id: '2',
        //   name: '李四',
        //   tel: '1310000000',
        //   address: '浙江省杭州市拱墅区莫干山路 50 号'
        // }
      ]
    }
  },
  created () {
    this.getAddressList()
  },
  methods: {
    listshow () {
      this.myshow = !this.myshow
      // console.log(this.myshow)
    },
    // 点击地址
    onitem () {
      // console.log(this.chosenAddressId)
      // console.log(this.list)
      const item = this.list.find(item => {
        return item.id === this.chosenAddressId
      })
      // console.log(item)
      this.listitem(item)
      this.$router.go(-1)
    },
    listitem (item) {
      const index = this.list.indexOf(item)
      if (index !== -1) {
        // console.log(item)
        // 存在相同项，将原有关键词移除
        // splice (从哪开始，删除几个)
        this.list.splice(index, 1)
      }
      this.list.unshift(item)
    },
    // 新增地址
    onAdd () {
      this.$router.push({
        path: '/addressadd',
        query: {
          edit: false
        }
      })
    },
    // 编辑地址
    onEdit (item, index) {
      this.$toast('编辑地址:' + index)
      // console.log(item.id)
      // console.log(item.name)
      // console.log(item.tel)
      // console.log(item.address)
      // console.log(item.isDefault)
      this.$router.push({
        path: '/addressadd',
        query: {
          edit: true,
          id: item.id,
          name: item.name,
          tel: item.tel,
          address: item.address,
          isDefault: item.isDefault
        }

      })
    },
    // 获取地址列表
    async getAddressList () {
      const { data: { list } } = await getAddressList()
      // console.log(list)
      if (list[0]) {
        list[0].isDefault = true

        this.chosenAddressId = list[0].address_id

        this.list = list.map(item => {
          const data = {
            id: item.address_id,
            name: item.name,
            tel: item.phone,
            address: `${item.region.city}/${item.region.province}/${item.region.region}/${item.detail} `,
            isDefault: item.isDefault
          }
          return data
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>
